﻿using BusinessLayer.DatabaseEntities;
using CustomerServiceCenter.Models;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace CustomerServiceCenter.Helper
{
    public class WeChatHelper
    {
        //string corpid = ConfigurationManager.AppSettings["CorpID"].ToString();
        //string corpsecret = ConfigurationManager.AppSettings["Secret"].ToString();

        private static string access_token = "";
        private static DateTime last_token_time;
        private static long client_id = 0;
        private static HttpCookie cookie = null;


        public string GetToken(Client client)
        {
            //使用Cookies保存对象
            cookie = HttpContext.Current.Request.Cookies["token"];
            if (cookie != null)
            {
                var cookie_entity = JsonHelper.ParseFromJson<CookieEntity>(cookie.Value) as CookieEntity;
                if (string.IsNullOrEmpty(cookie_entity.Access_Token) && DateTime.Now <= cookie_entity.Last_Token.AddMinutes(29) && client.ID == cookie_entity.ClientID)
                {
                    return cookie_entity.Access_Token;
                }
                else
                {
                    return GetTokenFromWeChat(client);
                }
            }
            else
            {
                return GetTokenFromWeChat(client);
            }
        }
        private static string GetTokenFromWeChat(Client client)
        {
            client_id = client.ID;
            //代码隐藏
            #region  refer http://www.cnblogs.com/HappyAnt/p/5207739.html; 

            //服务号
            //string url = String.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", client.CropID, client.Secret);

            //企业号
            string url = String.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", client.CropID, client.Secret);
            LogHelper.Info("get access_token url： " + url);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = "GET";
            using (WebResponse wr = req.GetResponse())
            {
                StreamReader streamReader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
                string content = streamReader.ReadToEnd();
                LogHelper.Info("get content： " + content);
                streamReader.Close();
                streamReader.Dispose();

                //在这里对Access_token 赋值
                AccessToken token = new AccessToken();
                token = JsonHelper.ParseFromJson<AccessToken>(content);
                last_token_time = DateTime.Now;
                access_token = token.access_token;
                //封装cookie
                cookie = new HttpCookie("token");
                CookieEntity cookie_entity = new CookieEntity
                {
                    Access_Token = access_token,
                    ClientID = client_id,
                    Last_Token = last_token_time
                };
                cookie.Value = JsonHelper.GetJson<CookieEntity>(cookie_entity);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            LogHelper.Info("WeChatHelper中的Access_token：" + access_token + "\r\n");
            return access_token;
            #endregion
        }


        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg"></param>
        public void SendMessage(WeiXinMessage msg, Client client)
        {
            string responseMsg = "{\"agentid\":" + client.APPID + ","
                                 + "\"touser\":" + "\"" + msg.ToUserName + "\"" + ","
                                 + "\"msgtype\":" + "\"text\"" + ","
                                 + "\"text\":{" + "\"content\":" + "\"" + msg.MsgContent + "\"" + "},"
                                 + "\"safe\":" + 0
                                 + "}";
            string url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + GetToken(client);
            LogHelper.Info("发送的消息:" + responseMsg);
            ProcessSendMessage(responseMsg, url);
        }

        ///<summary>
        ///服务号发送消息
        /// </summary>
        /// <param name="msg"></param>
        public void SendServiceMessage(WeiXinMessage msg, Client client)
        {
            string responseMsg = "{\"touser\":" + "\"" + msg.openid + "\"" + ","
                                 + "\"msgtype\":" + "\"text\"" + ","
                                 + "\"text\":{" + "\"content\":" + "\"" + msg.MsgContent + "\"" + "},"
                                 + "}";
            string url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + GetToken(client);
            LogHelper.Info("send message :" + responseMsg);
            ProcessSendMessage(responseMsg, url);
        }

        public void SendTemplateMessage(WeiXinMessage msg, Client client,string uri)
        {
            //            +"\"toparty\" :" + " \"PartyID1 | PartyID2\"" + ","
            //            + "\"totag\" : " + " \"PartyID1 | PartyID2\"" + ","
            string responseMsg = "{\"touser\" :" + "\"" + msg.openid + "\"" +","
               + "\"msgtype\" : " + " \"textcard\""+","
               + "\"agentid\" :"+" \"1\""+","
               + "\"textcard\" : " + "{"
               + "\"title\" :" + " \"领奖通知\""+","
               +"\"description\" : "+"\"<div class=\"gray\">2016年9月26日</div> <div class=\"normal\">"+msg.MsgContent+"</div>\"" +","
                        +"\"url\" :"+" \"URL\""+","
                        +"\"btntxt\":"+"\"更多\""
                    +"}}";
            string url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + GetToken(client);
            LogHelper.Info("send message :" + responseMsg);
            ProcessSendMessage(responseMsg, url);
        }

         


        /// <summary>
        /// 处理消息发送
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="url"></param>
        void ProcessSendMessage(string msg, string url)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(msg);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "json";
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            request.Timeout = 90000;
            request.Headers.Set("Pragma", "no-cache");

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream respStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
            string result = reader.ReadToEnd();

            respStream.Dispose();
            reader.Dispose();
            LogHelper.Info("发送的结果：" + result);
        }

        public static string SendPost(string userurl)
        {

            HttpWebRequest hwr = WebRequest.Create(userurl) as HttpWebRequest;
            hwr.Method = "POST";
            hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
            hwr.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            var result = hwr.GetResponse() as HttpWebResponse;
            StreamReader reader = new StreamReader(result.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();
            return content;
        }

    }
}